import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:redux/redux.dart';
import 'package:stock_check/common/config/Config.dart';
import 'package:stock_check/common/dao/TasksDao.dart';
import 'package:stock_check/common/dao/UserDao.dart';
import 'package:stock_check/common/dao/WorksDao.dart';
import 'package:stock_check/common/model/checkITDeviceItem.dart';
import 'package:stock_check/common/model/taskItem.dart';
import 'package:stock_check/common/model/userInfo.dart';
import 'package:stock_check/common/redux/CheckDevicesReducer.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/storage/LocalStorage.dart';
import 'package:stock_check/common/utils/CommonUtils.dart';
import 'package:stock_check/common/utils/NavigatorUtils.dart';
import 'package:stock_check/widget/CommonsWidget.dart';
import 'package:stock_check/widget/MyScaffold.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';

/// 我的任务首页
class HomePage extends StatefulWidget {
  static final String routeName = '/home';

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin  {
  bool hadInitLoginInfo = false;
  Store<StockState> store;
  List<CheckITDeviceItem> itList = new List();
  List<CheckITDeviceItem> institutionsList = new List();
  List<TaskItem> tasks = new List();
  final formatter = new DateFormat('yyyy-MM-dd');
//  AnimationController _animationController;
//  Animation<double> animation;
  int type = 0;

  // 强制刷新数据
  Future<VoidCallback> _pullToRefresh() async {
    _initWorks();
    _updateStoreData();
    return null;
  }

  @override
  void initState() {
    super.initState();
//    _animationController = new AnimationController(vsync: this, duration: Duration(seconds: 2));
//    animation = new Tween(begin: 0.0, end: 0.0).animate(_animationController);
    _initWorks();
  }

  @override
  void dispose() {
//    _animationController.dispose();
    super.dispose();
  }

  void updateTime()async{
    String updateTime = formatter.format(DateTime.now());
    // 更新数据更新时间
    await LocalStorage.save(Config.LAST_UPDATE,updateTime);
    store.dispatch(UpdateLastUpdateDay(dateStr:updateTime));
  }

  // 更新盘点数据
  void updateTaskStoreData() async{
    // 更新盘点设备
    store.dispatch(UpdateTasksAction(tasks: tasks));
    updateTime();
  }

  /// 更新全局数据
  void _updateStoreData() async{
    // 更新待巡检设备列表
    store.dispatch(UpdateCheckITDevicesAction(checkITDeviceItems: itList));
    // 更新待巡检设施设备列表
    store.dispatch(UpdateCheckInstitutionsAction(checkInstitutionItems: institutionsList));
    updateTime();
  }

  /// 更新当前数据
  void _initWorks() async{
    if(await CommonUtils.getNetStatus()){
      String userTxt = await LocalStorage.get(Config.USER_INFO);
      if(userTxt!=null){
        String updateTime = formatter.format(DateTime.now());
        UserInfo userInfo = UserInfo.fromJson(json.decode(userTxt));
        try{
          // 更新盘点任务
          tasks = await TasksDao.getTasksList(userInfo.deptId,updateTime);
          // 更新选件任务
          var needCheckITDevices = await WorksDao.getNeedCheckITDevicesList(userInfo.deptId,updateTime);
          var needCheckInstitutionDevices = await WorksDao.getNeedCheckInstitutionsList(userInfo.deptId,updateTime);
          if(needCheckInstitutionDevices.data!=null)
            itList = needCheckITDevices.data;
          if(needCheckInstitutionDevices.data!=null)
            institutionsList = needCheckInstitutionDevices.data;
          if(itList.length!=0){
            type = 0;
          }else if(institutionsList.length!=0){
            type = 1;
          }else{
            type = 3;
          }
          // 防止除0错误
//          if((itList.length+institutionsList.length)!=0){
//            if(institutionsList.length!=0) {
//              end = itList.length / (itList.length + institutionsList.length);
//            }else{
//              end = 0.0;
//            }
//          }else{
//            type = 2;
//          }
//          _animation(end);
          Fluttertoast.showToast(msg: '数据已更新...');
          setState(() {

          });
        }catch(e){
          tasks = new List();
          itList = new List();;
          institutionsList = new List();
          Fluttertoast.showToast(msg: '服务器发生故障...');
        }
      }else{
//        _animation(0.0);
        NavigatorUtils.goLogin(context);
      }
    }else{
      Fluttertoast.showToast(msg: '未连接互联网...');
    }
  }



  // 初始化参数
  _initParams() async{
    UserDao.needUpdate().then((bool)async{
      if(bool) {
        _initWorks();
        await LocalStorage.save(Config.LAST_UPDATE,formatter.format(DateTime.now()));
      };
    });
    // 防止多次进入
    store = StoreProvider.of(context);
    if(!hadInitLoginInfo)
    UserDao.initAppInfo(store).then((res) {
      // 如果用户信息没有了,说明软件没有使用过
      if (res.data == null || res.result == false) {
        hadInitLoginInfo = false;
      }else{
        hadInitLoginInfo = true;
      }
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 判断用户登陆情况,以及有没有数据需要更新
    _initParams();
  }

  @override
  Widget build(BuildContext context) {
    final accentColor = Theme.of(context).accentColor;
    return StoreBuilder<StockState>(builder: (context, store) {
      return Container(
          child: MyScaffold(
        title: Text("我的任务"),
        child: Container(
            child: WillPopScope(
            onWillPop: () => CommonsWidget.dialogExitApp(context,'是否退出?'),
            child: RefreshIndicator(
                onRefresh: _pullToRefresh,
                child: ListView(
                  children: <Widget>[
                    Padding(padding: EdgeInsets.only(top: 10.0)),
                    Card(
                      elevation: 1.5,
                      child: ListTile(
                        title: Row(
                          children: <Widget>[
                            Icon(Icons.assignment, color: accentColor),
                            Text(
                              " 盘点项目",
                              style: TextStyle(color: accentColor),
                            )
                          ],
                        ),
                        trailing: Container(
                          width: 25.0,
                          height: 25.0,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Theme.of(context).accentColor, shape: BoxShape.circle),
                          child: Text("${tasks.length}", style: TextStyle(color: Colors.white)),
                        ),
                        onTap: (){
                          if(tasks.length>0){
                            updateTaskStoreData();
                            NavigatorUtils.goCheckWork(context);
                          }else{
                            Fluttertoast.showToast(msg: "今日没有盘点任务!");
                          }
                        },
                      ),
                    ),
                    InkWell(
                      onTap: (){
                        // 看看本地刚刚的下载的数据的数量
                        if(itList.length+institutionsList.length>0) {
                          // 更新全局数据
                          _updateStoreData();
                          NavigatorUtils.goCheckDevicesListPage(context,type==0?'IT类':'巡检类');
                        }else{
                          Fluttertoast.showToast(msg: "今日没有巡检任务!");
                        }
                      },
                      highlightColor:Colors.white,
                      child: Card(
                        elevation: 1.5,
                        child:_renderCheck(accentColor),
                      ),
                    ),
                    Container(
                      alignment: Alignment.center,
                      child: Text('下拉可刷新...',style: TextStyle(color: Colors.grey,fontSize: 13.0),),
                    )
                  ],
                )),
        )),
        store: store,
      ));
    });
  }

  Widget _renderCheck(color){
      var title;
      var count = 0;
      if(type == 0){
        title = 'IT';
        count = itList.length;
      }else if(type == 1){
        title = '设备';
        count = institutionsList.length;
      }else{
        title = '暂无任务';
        count = 0;
      }
      return ListTile(
            title: Row(
              children: <Widget>[
                Icon(Icons.assignment,color: color,),
                Text(
                  " ${title}巡检",
                  style: TextStyle(color: color),
                )
              ],
            ),
            trailing: Container(
              width: 25.0,
              height: 25.0,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Theme.of(context).accentColor, shape: BoxShape.circle),
              child: Text("${count}", style: TextStyle(color: Colors.white)),
            ),
          );

//    return SizedBox(
//      height: 120.0,
//      width: 120.0,
//      child: Stack(
//        alignment: Alignment.center,
//        children: <Widget>[
//          Positioned(
//            left: 0.0,
//            height: 120.0,
//            top: .0,
//            child: GradientCircularProgressIndicator(
//                colors: [Colors.teal, Colors.cyan[500]],
//                backgroundColor: Colors.blue[100],
//                radius: 60.0,
//                stokeWidth: 20.0,
//                value: animation.value,
//                totalAngle: pi*2
//            ),
//          ),
//          Positioned(
//            left: 30.0,
//            child:  Text(
//              "巡检项目",
//              style: TextStyle(
//                fontSize: 15.0,
//                color:Theme.of(context).accentColor,
//              ),
//            ),
//          ),
//          Positioned(
//            height: 120.0,
//            right: 20.0,
//            bottom: 0.0,
//            child: Column(
//              crossAxisAlignment: CrossAxisAlignment.start,
//              children: <Widget>[
//                Row(
//                  children: <Widget>[
//                    SizedBox(
//                      width: 20.0,
//                      height: 20.0,
//                      child: Container(
//                        color: Colors.teal[400],
//                      ),
//                    ),
//                    Text('  IT设备${itList.length}项,占比${_get(itList.length)}',style: TextStyle(color: Colors.green),)
//                  ],
//                ),
//                Padding(padding: EdgeInsets.all(8.0),),
//                Row(
//                  children: <Widget>[
//                    SizedBox(
//                      width: 20.0,
//                      height: 20.0,
//                      child: Container(
//                        color: Colors.blue[100],
//                      ),
//                    ),
//                    Text('  设施${institutionsList.length}项,占比${_get(institutionsList.length)}',style: TextStyle(color: Colors.green),)
//                  ],
//                ),
//                Padding(padding: EdgeInsets.all(8.0),),
//                Row(
//                  children: <Widget>[
//                    SizedBox(
//                      width: 20.0,
//                      height: 20.0,
//                      child: Container(
//                        color: Colors.deepOrange
//                      ),
//                    ),
//                    Text('  总计${itList.length+institutionsList.length}项',style: TextStyle(color: Colors.green),)
//                  ],
//                ),
//              ],
//            ),
//          )
//        ],
//      ),
//    );
  }

  _get(int i) {
    if(itList.length!=0&&institutionsList.length!=0)
      return ((i/(itList.length+institutionsList.length))*100).toStringAsFixed(1)+"%";
    else
      return "0%";
  }

  void _animation(double end) {
//    animation = new Tween(begin: 0.0, end: end).animate(_animationController)
//      ..addListener(() {
//        setState(()=>{});
//      });
//    if(_animationController.status == AnimationStatus.completed){
//      _animationController.reset();
//    }
//    _animationController.forward();
  }

}


//                    ListTile(
//                        leading: Icon(
//                          Icons.check_box,
//                          color: accentColor,
//                        ),
//                        title: Text(
//                          "巡检",
//                          style: TextStyle(color: accentColor),
//                        ),
//                        trailing: Text('IT设备[${itList.length}项],设施[${institutionsList.length}项]',style:TextStyle(
//                            color: Colors.teal,
//                            fontSize: 16.0
//                        )),
//                        onTap: () async{
//                          // 看看本地刚刚的下载的数据的数量
//                          if(itList.length+institutionsList.length>0) {
//                            // 更新全局数据
//                            _updateStoreData();
//                            NavigatorUtils.goCheckDevicesListPage(context,itList,institutionsList);
//                          }else{
//                            Fluttertoast.showToast(msg: "今日没有任务!");
//                          }
//                        }),